package com.sytc.camera.test;

import com.sytc.camera.util.Util;
import org.junit.Test;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 从dat文件中获取图像包
 */
public class ImageExtractor {
    //    private static final byte[] FRAME_HEADER = new byte[]{(byte) 0x57, (byte) 0x6A, (byte) 0x2D, (byte) 0xE8};  // 小端：E82D6A57
//    private static final byte[] FRAME_FOOTER = new byte[]{(byte) 0x3C, (byte) 0x7E, (byte) 0xBA, (byte) 0x20};      private static final byte[] FRAME_HEADER = new byte[]{(byte) 0x57, (byte) 0x6A, (byte) 0x2D, (byte) 0xE8};  // 小端：E82D6A57
    private static final byte[] FRAME_HEADER = new byte[]{(byte) 0xE8, (byte) 0x2D, (byte) 0x6A, (byte) 0x57};  // 小端：E82D6A57
    private static final byte[] FRAME_FOOTER = new byte[]{(byte) 0x20, (byte) 0xBA, (byte) 0x7E, (byte) 0x3C};  // 小端：20BA7E3C
    private static final int IMAGE_WIDTH = 512;
    private static final int IMAGE_HEIGHT = 512;
    private static final int PIXEL_SIZE = 2;  // 每个像素2字节（高8位+低8位）
    String outputFile = "E:\\project\\sytc_camera\\out\\datfile\\file20241221_224537_866.txt";

    @Test
    public void xxx(){

        String inputFilePath = "E:\\project\\sytc_camera\\out\\datfile\\file20241221_224537_866.dat";
        String outputDirectory = "E:\\project\\sytc_camera\\out\\datfile\\image";


//        String inputFilePath = "E:\\project\\USBImgProcess系统文件夹\\123.dat";
//        String outputDirectory = "E:\\project\\USBImgProcess系统文件夹\\image";

        try {
            // 读取文件字节流
            byte[] fileBytes = Files.readAllBytes(Paths.get(inputFilePath));
            List<byte[]> images = extractImages(fileBytes);

            // 保存提取出来的每个图像
            for (int i = 0; i < images.size(); i++) {
                saveImageToFile(images.get(i), outputDirectory, i);
            }

            System.out.println("图像提取完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提取图像数据
     * @param fileBytes 完整的文件字节流
     * @return 每一条图像的字节数组列表
     */
    private List<byte[]> extractImages(byte[] fileBytes) {
        List<byte[]> images = new ArrayList<>();
        int currentIndex = 0;
        int imagePacketNum = 0;

        try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {



        while (currentIndex < fileBytes.length) {
            // 查找帧头
            int frameHeaderIndex = Util.indexOf(fileBytes, FRAME_HEADER, currentIndex);
            if (frameHeaderIndex == -1) break;  // 没有找到帧头，结束提取

            // 查找帧尾
            int frameFooterIndex = Util.indexOf(fileBytes, FRAME_FOOTER, frameHeaderIndex);
            if (frameFooterIndex == -1) break;  // 没有找到帧尾，结束提取

            // 打印frameFooterIndex和frameFooterIndex还有两个之间的差值
            System.out.println("frameHeaderIndex: " + frameHeaderIndex + ", frameFooterIndex: " + frameFooterIndex + ", diff: " + (frameFooterIndex - frameHeaderIndex+4));

            writer.write("\n第" + (++imagePacketNum) + "个image包\theadIndex:" + frameHeaderIndex+"\ttailIndex:" + frameFooterIndex + "\tlength:"+(frameFooterIndex-frameHeaderIndex+4));


            // 计算帧的数据部分大小：帧头 + 图像数据 + 帧尾
            // 验证帧数据的有效性
            byte[] imageBytes = new byte[frameFooterIndex - frameHeaderIndex -70 -4 -2];
            System.arraycopy(fileBytes, frameHeaderIndex + 70 + 4, imageBytes, 0, imageBytes.length);
            images.add(imageBytes);  // 添加图像数据

            // 更新当前索引，继续查找下一帧
            currentIndex = frameFooterIndex + FRAME_FOOTER.length;
        }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return images;
    }


    /**
     * 保存图像数据到文件
     * @param imageBytes 图像数据
     * @param outputDirectory 输出目录
     * @param index 图像索引
     */
    private static void saveImageToFile(byte[] imageBytes, String outputDirectory, int index) {
        try {
            // 确保输出目录存在
            File dir = new File(outputDirectory);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 构建输出文件路径
            String outputFilePath = outputDirectory + "/image_" + index + ".raw";
            try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                fos.write(imageBytes);
                System.out.println("保存图像 " + index + " 到文件: " + outputFilePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
